package com.hong.utils.executors;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Auther: Administrator
 * @Date: 2018/7/29 20:55
 * @Description:
 */
public class ScheduledExecutorServiceExample2 {
    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
        /**
         * 创建并执行在给定的初始延迟之后首先启用的定期动作，随后在一个执行的终止和下一个执行的开始之间给定的延迟。
         * 如果任务的执行遇到异常，则后续的执行被抑制。 否则，任务将仅通过取消或终止执行人终止。
         *
         * command - 要执行的任务
         * initialDelay - 延迟第一次执行的时间
         * delay - 一个执行终止和下一个执行的开始之间的延迟
         * unit - initialDelay和delay参数的时间单位
         */
       /* executor.scheduleWithFixedDelay(()->
            System.out.println("==="+System.currentTimeMillis())
        ,1,2,TimeUnit.SECONDS);*/

       /* final AtomicLong interval = new AtomicLong(0L);
        ScheduledFuture<?> futures= executor.scheduleAtFixedRate(()->{
            long currentTimeMillis =    System.currentTimeMillis();
            if(interval.get() == 0){
                System.out.printf("The first time trigger task at %d\n",currentTimeMillis);
            }else{
                System.out.printf("The actually spend [%d]\n",currentTimeMillis-interval.get());
            }
            interval.set(currentTimeMillis);
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },1,2,TimeUnit.SECONDS);*/
        test2();


    }

    public static void test2() throws InterruptedException {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
        System.out.println(executor.getExecuteExistingDelayedTasksAfterShutdownPolicy());
        executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        final AtomicLong interval = new AtomicLong(0L);
        ScheduledFuture<?> future = executor.scheduleWithFixedDelay(()->{
            long currentTimeMillis =    System.currentTimeMillis();
            if(interval.get() == 0){
                System.out.printf("The first time trigger task at %d\n",currentTimeMillis);
            }else{
                System.out.printf("The actually spend [%d]\n",currentTimeMillis-interval.get());
            }
            interval.set(currentTimeMillis);
            System.out.println(Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },1,2,TimeUnit.SECONDS);
        TimeUnit.MILLISECONDS.sleep(1200);
        executor.shutdown();
        System.out.println("===over====  ");
    }
}
